#include<iostream>
#include<vector>
using namespace std;

long long maxWater(vector<int>& arr) {
    int n = arr.size();
    if (n <= 2) return 0;
    int left = 1, right = n - 2;

    int l_max = arr[0];
    int r_max = arr[n - 1];
    int ret = 0;

    while (left <= right) {
        l_max = max(l_max, arr[left]);
        r_max = max(r_max, arr[right]);

        if (l_max < r_max) {
            ret += l_max - arr[left++];
        }
        else {
            ret += r_max - arr[right--];
        }
    }

    return ret;
}

int main()
{
    vector<int>arr = { 3,0,1,5,2,4 };
    cout << maxWater(arr) << endl;
    return 0;
}